<template>
  <div>
    <div class="title rounded shadow-harsh bar">
      <div>用户管理</div>
      <div class="flex-row">
        <el-input
          class="mr-10"
          v-model="search"
          size="mini"
          placeholder="输入用户名搜索" />
        <el-button
          @click="dialogFormVisible = true"
          size="mini"
          type="success">新增
        </el-button>
      </div>
    </div>

    <div class="mt-30">
      <!--    通过字段进行 filter-->
      <el-table
        height="450px"
        class="shadow-harsh rounded p-5"
        v-loading="loading"
        :data="tableData.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase())).slice((currentPage-1)*10,currentPage*10)"
      >
        <el-table-column
          label="用户名"
          prop="username"
        >
          <template scope="scope">
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row.username" placeholder="请输入内容">
            </el-input>
            <span v-else>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="权限"
          prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.$index !== editIndex" size="medium" :disable-transitions="true">{{ roleEncoder(scope.row.status) }}
            </el-tag>
            <el-select size="small" v-else v-model="scope.row.status" placeholder="请选择">
              <el-option
                v-for="item in lvls"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          label="最后登录时间"
          prop="lastLoginTime">
        </el-table-column>
        <el-table-column
          label="启用时间"
          prop="createTime">
        </el-table-column>
        <el-table-column
          width="350px"
          align="right">

          <template slot-scope="scope">
            <!--            <el-button-->
            <!--              size="mini"-->
            <!--              @click="rowClickHandler(scope.row)">查看-->
            <!--            </el-button>-->
            <span v-if="scope.$index !== editIndex">

              <el-button
                @click="clickConfig(scope.$index, scope.row)"
                v-if="(scope.row.status).indexOf('worker') !== -1"
                size="mini"
                type="primary"
              >专员权限配置
            </el-button>
              <el-button
                style="margin-right: 10px"
                size="mini"
                type="warning"
                @click="clickEdit(scope.$index, scope.row)">修改
              </el-button>


              <el-popconfirm
                @confirm="handleDelete(scope.$index, scope.row)"
                title="您确定要删除用户吗?">
                <el-button
                  slot="reference"
                  size="mini"
                  type="danger">删除
                </el-button>
              </el-popconfirm>
            </span>
            <span v-else>

            <el-button
              size="mini"
              type="success"
              @click="handleEdit(scope.$index, scope.row)">保存
            </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="editIndex = null">取消
              </el-button>

              </span>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="pagination"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-size="10"
                     :total="tableData.length"
                     layout="total, prev, pager, next, jumper">
      </el-pagination>

    </div>

    <el-dialog title="新增用户" :visible.sync="dialogFormVisible">
      <div class="hint">
        *用户名与密码必须包含数字和大小写字母，且用户名4-12位，密码8-16位。
      </div>
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="权限" :label-width="formLabelWidth">
          <el-select class="w-100" v-model="form.lvl" placeholder="请选用户权限">
            <el-option
              v-for="item in lvls"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth">
          <el-input v-model="form._password" show-password></el-input>
          <div class="warn" v-show="judgePassword">
            两次输入不一致
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button :disabled="!judgeValidity" type="primary" @click="handleSubmitAdd">确 定</el-button>
      </div>
    </el-dialog>


<!--    config modal-->
    <el-dialog title="权限配置" :visible.sync="config.confDialogFormVisible">
      <h2>正在配置<span style="color:#1619f3;">{{ config.userInfo.nickname }}</span>的权限</h2>

      <div class="flex-space-between">
        <div>
          <h2>表格权限</h2>
          <div v-for="(ele, index) in this.config.tableAuthorization" :key="index">
            <el-button
              @click="configPermission(ele)"
              style="width: 200px"
              size="mini" :type="ele.has?'primary':'default'">{{ ele.value }}</el-button>
          </div>

        </div>

        <div>
          <h2>文档权限</h2>
          <div v-for="(ele, index) in this.config.documentAuthorization" :key="index">
            <el-button
              @click="configPermission(ele)"
              style="width: 200px"
              size="mini" :type="ele.has?'primary':'default'">{{ ele.value }}</el-button>
          </div>

        </div>
      </div>

      <div slot="footer" class="dialog-footer">
<!--        <el-button @click="config.confDialogFormVisible = false">取 消</el-button>-->
        <el-button @click="config.confDialogFormVisible = false" type="primary">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getRoleByEN } from "../../../common/role";
import { tables, documents } from "../../../common/table";
import { authorization, viewNEdit } from "../../../common/role";

export default {
  name: "UserInfo",
  mounted() {
    this.loading = true;
    this.$api.getAllUsers().then(res => {
      // console.log('users', res)
      this.tableData = res.data.records;
      this.loading = false;
    });
  },
  computed: {
    judgePassword: function() {
      return this.form._password && (this.form._password !== this.form.password);
    },
    judgeValidity: function() {
      let usernamePattern = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{4,12}$/
      let passwordPattern = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/
      return usernamePattern.test(this.form.username)
          && passwordPattern.test(this.form.password)
          && (this.form._password === this.form.password)
    },


  },
  methods: {
    roleEncoder(role) {
      let arr = role.split(':')
      return getRoleByEN(arr[0], arr[1])
    },

    handleSubmitAdd() {
      // 提交注册信息

      let o = {
        "avatar": "",
        "id": "",

        "nickname": this.form.username,
        "username": this.form.username,
        "password": this.form.password,
        "status": this.form.lvl,
        "updateTime": "string",
        "lastLoginTime": "",
        "createTime": "",
      }

      this.$api.editUser('save', '', o).then(res => {
        console.log(res)
        if (res['success']) {
          this.dialogFormVisible = false
          this.form = {
            username: "",
            lvl: "",
            password: "",
            _password: ""
          }
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 2000
          });

          this.tableData.push(res.data['user'])
        }

      })

    },

    handleEdit(index, row) {
      // TODO 完成信息的行内修改模块


      let o = {
        "avatar": "",
        "id": "",

        "nickname": row.username,
        "username": row.username,
        "password": "",
        "status": row.status,
        "updateTime": "",
        "lastLoginTime": "",
        "createTime": "",
      }

      console.log("new", index, row, o);
      this.$api.editUser('update', row.id, o).then(res => {
        console.log(res)
        if (res['success']) {
          this.$message({
            message: '修改成功',
            type: 'success',
            duration: 2000
          });
        }
      })

      this.editIndex = null;
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$api.editUser('remove', row.id, {
        "avatar": "",
        "id": 0,
        "nickname": '',
        "username": '',
        "password": '',
        "status": '',
        "updateTime": "string",
        "lastLoginTime": "",
        "createTime": "",
      }).then(res => {
        console.log(res)
        if (res['success']) {

          let n =index + 1 + (this.currentPage-1) * 10
          this.tableData.splice(n-1, 1)


          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
        }
      })

    },
    clickConfig(index, row) {
      this.config.confDialogFormVisible = true
      this.config.userInfo = row



      this.$api.getAuthorization(row.id).then(res => {
        console.log('au', index, res)
        this.config.permissions = res.data.permission

        let tableAuthorization = []
        let documentAuthorization = []
        // this.config.permissions
        this.config.permissions.forEach(ele => {
          console.log(ele)
        })

        tables.forEach(table => {
          authorization.forEach(au => {
            let name = `${table.name}:${au.name}`
            tableAuthorization.push({
              'name': name,
              'value': `${table.label}:${au.value}`,
              'has': this.config.permissions.find(ele => {
                return  ele.permission === name
              })
            })
          })
        })

        documents.forEach(table => {
          viewNEdit.forEach(au => {
            let name = `${table.name}:${au.name}`
            documentAuthorization.push({
              'name': name,
              'value': `${table.label}:${au.value}`,
              'has': this.config.permissions.find(ele => {
                return  ele.permission === name
              })
            })
          })
        })


        this.config.tableAuthorization = tableAuthorization
        this.config.documentAuthorization = documentAuthorization

      })
    },

    clickEdit(index, row) {
      console.log(row);
      this.editIndex = index;
    },
    clickAdd() {

    },
    configPermission: function(permission) {
      console.log(permission)
      if (permission.has) {
        // 存在即删除
        this.$api.editAuthorization('remove', permission.has.id, {}).then(res => {
          console.log('remove', res)

          if (res['success']) {

            this.$message({
              message: '删除权限成功',
              type: 'success',
              duration: 2000
            });

            permission.has = null
          }

        })
      } else {
        // 保存权限
        this.$api.editAuthorization('save', 0, {
          "createTime": "",
          "id": 0,
          "permission": permission.name,
          "updateTime": "",
          "userId": this.config.userInfo.id
        }).then(res => {
          console.log('save', res)
          if (res['success']){
            this.$message({
              message: '增加权限成功',
              type: 'success',
              duration: 2000
            });
            let n = res.data.authorities.length
            permission.has = res.data.authorities[n-1]
          }



        })
      }



    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
    },

  },

  data() {
    return {

      config: {
        confDialogFormVisible: false,
        permissions: [],
        userInfo: {},

        tableAuthorization: [],
        documentAuthorization: []
      },


      tableData: [],
      currentPage: 1,
      search: "",
      editIndex: null,
      loading: true,

      // dialogTableVisible: false,
      dialogFormVisible: false,
      formLabelWidth: "100px",
      form: {
        username: "",
        lvl: "",
        password: "",
        _password: ""
      },

      lvls: [
        // 权限见文档
        {
          value: "none:root",
          label: "-:超级管理员"
        }, {
          value: "product_center:director",
          label: "产品中心部门:总监"
        }, {
          value: "product_center:worker",
          label: "产品中心部门:专员"
        }, {
          value: "quality_center:director",
          label: "质量中心部门:总监"
        }, {
          value: "quality_center:worker",
          label: "质量中心部门:专员"
        }, {
          value: "none:user",
          label: "-:成员"
        },
      ],
      test: ""
    };
  }
};
</script>

<style scoped>
.hint {
  /*color: red;*/
  margin-bottom: 30px;
  text-align: center;
}

h2{
  text-align: center;
}


.flex-space-between {
  padding: 0 30px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>